package tk.pak0.audiomidifier.controller;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;

import org.apache.log4j.Logger;

import tk.pak0.audiomidifier.model.persistence.A_DataHolder;
import tk.pak0.audiomidifier.model.persistence.XmlDataHolder;
import tk.pak0.audiomidifier.view.MainWindow;

public class StartThread implements Runnable{
	private static Logger log = Logger.getLogger(StartThread.class);
	public void run() {
		MainWindow frame = new MainWindow();
		frame.setDefaultCloseOperation(MainWindow.DO_NOTHING_ON_CLOSE);
		frame.setTitle("Audiomidifier");
		frame.getContentPane().setPreferredSize(frame.getSize());
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
		frame.addWindowListener(new WindowListener() {
			
			public void windowOpened(WindowEvent arg0) {}
			public void windowIconified(WindowEvent arg0) {}
			public void windowDeiconified(WindowEvent arg0) {}			
			public void windowDeactivated(WindowEvent arg0) {}
			public void windowActivated(WindowEvent arg0) {}
			public void windowClosed(WindowEvent arg0) {}
			public void windowClosing(WindowEvent arg0) {
				// make options persistent
				A_DataHolder a_DataHolder = XmlDataHolder.getInstance();
				MainWindow frame = (MainWindow)arg0.getSource();
				a_DataHolder.setValues(frame.getValues());
				try {
					a_DataHolder.makePersistent();
				} catch (IOException e) {
					log.error("Escritura de persistencia fallida");
					e.printStackTrace();
				}finally{
					arg0.getWindow().dispose();
				}
				arg0.getWindow().dispose();
			}
		});
	}

}
